import java.util.List;

import java.io.Serializable;

import static org.jboss.seam.ScopeType.EVENT;

import javax.ejb.Remove;
import javax.ejb.Stateless;
import javax.ejb.Stateful;
import javax.persistence.PersistenceUnit;
import javax.persistence.PersistenceContext;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import org.jboss.seam.ScopeType;
import org.jboss.seam.annotations.Destroy;
import org.jboss.seam.annotations.AutoCreate;
import org.jboss.seam.annotations.Scope;
import org.jboss.seam.annotations.Name;
import org.jboss.seam.annotations.In;
import javax.ejb.Remove;
import org.jboss.seam.faces.FacesMessages;



@Stateful
//@Scope(ScopeType.SESSION)
@Scope(EVENT)
//@Stateless 
@Name("register")
//@Scope(ScopeType.STATELESS)
//@AutoCreate
public class RegisterAction implements Register, Serializable
{
   @In
   private User user;
   
   @PersistenceUnit
   private EntityManagerFactory entityManagerFactory;
   
   //@PersistenceContext
   //private EntityManager em;
   
   //@Logger
   //private Log log;

   //@Remove
   //@In
   public String register()
   { 
	if ( null == entityManagerFactory ) {
                        System.out.println( "entityManagerFactory is hosed" );
        }
      //EntityManager entityManager = entityManagerFactory.createEntityManager();

      System.out.println("!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!" + user.getUsername());
      //System.out.println("!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!select username from User where username = #{user.username}");
      //List existing = entityManager.createQuery(
      List existing = entityManagerFactory.createEntityManager().createQuery(
         "select u.username from User u where u.username = :username")
         .setParameter("username", user.getUsername())
         .getResultList();
         
      if (existing.size()==0)
     {
         System.out.println("!!!DOES NOT EXIST, CREATING!!!");
         //entityManager.persist(user);
         entityManagerFactory.createEntityManager().persist(user);
         //log.info("Registered new user #{user.username}");
         return "/registered.xhtml";
      } 
      else
      {
         System.out.println("!!!EXISTS, NOT CREATING!!!");
         FacesMessages.instance().add("User #{user.username} already exists");
         return null;
      }
   }

   @Destroy @Remove
   public void destroy() {}

}
